package cs342.project1.mathNotebook.gui;

import cs342.project1.mathNotebook.data.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;

public class LoginScreen extends JFrame {

    private final int width = 300, height = 100;
    private JTextField username;
    private JPasswordField password;
    private JLabel userLabel, passwordLabel;
    private JButton loginButton, cancelButton;
    
    public LoginScreen() {
        
        // Initial Frame Setup
        this.setSize(width, height);
        this.setTitle("Login");
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setLayout(new GridLayout(3,2));
        this.setResizable(false);
        
        userLabel = new JLabel("Username: ");
        this.add(userLabel);
        
        username = new JTextField(25);
        this.add(username);
        
        passwordLabel = new JLabel("Password: ");
        this.add(passwordLabel);
        
        password = new JPasswordField(25);
        this.add(password);
        
        loginButton = new JButton("Login");
        loginButton.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent ae) {
		try{
			hitLogin();
		}catch(Exception ex){
			ex.printStackTrace();
		}
        }});
        this.add(loginButton);
        this.getRootPane().setDefaultButton(loginButton);
        cancelButton = new JButton("Cancel");
        cancelButton.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e) {hitCancel();}});
        this.add(cancelButton);
    }

    private void hitLogin() throws SQLException{
        	MathDatabase mdb = new MathDatabase();
        	mdb.open();
        	String passwordString = new String(password.getPassword());
        	mdb.getStatement().executeQuery("SELECT * FROM Users WHERE username = "+'"' + username.getText() + '"' + " AND password = " + '"' + passwordString + '"');
        	ResultSet rs = mdb.getStatement().getResultSet();
        	if(rs.next()){
        		this.dispose();
        		new UserInterface(rs.getInt("userID")).setVisible(true);
        	}else{
        		username.setText("Incorrect Username or Password!");
        	}
        	mdb.close();
    }

    private void hitCancel(){
        	this.dispose();
        	new StartScreen().setVisible(true);
    }
}